<?php

class MallMaterialTemService
{

    /*
     * 菜单 和 模板 是否有关联
     *
     */
    public static function checkMaterialAndTem($template_id,$material_id)
    {
        $mall_tem_mat  = MallTemplateMaterial::model()->find("template_id=:template_id and  material_id=:material_id",
            array(":template_id" => $template_id,":material_id" => $material_id));

        if(empty($mall_tem_mat)==true)
            return 0;

        if($mall_tem_mat->is_delete == 1)
            return 0;

        return 1;
    }

    //设置 菜单和模板关系
    public static function setMaterialTemRelation($material_id,$selectlist,$unselectlist)
    {
        $connection=Yii::app()->db;

        $transaction=$connection->beginTransaction();//事物开始

        $sarray = explode(",",$selectlist);
        $usarray = explode(",",$unselectlist);

        try
        {
            //设置选中状态
            $l = count($sarray);

            for($i=0;$i<$l;$i++)
            {
                $template_id = $sarray[$i];

                MallMaterialTemService::addRelation($material_id,$template_id);

            }

            //取消选中状态
            $l = count($usarray);

            for($i=0;$i<$l;$i++)
            {
                $template_id = $usarray[$i];

                MallMaterialTemService::deleteRelation($material_id,$template_id);

            }


            $transaction->commit();//事物结束

        }
        catch(Exception $e)
        {
            $transaction->rollback();//回滚函数

            throw new Exception($e->getMessage());

        }

    }

    //设置选中
    public static function addRelation($material_id,$template_id)
    {
        $mall_tem_mat  = MallTemplateMaterial::model()->find("material_id=:material_id and  template_id=:template_id",
            array(":material_id" => $material_id,":template_id" => $template_id));

        if(empty($mall_tem_mat)==true)
        {
            //新建
            $mall_tem_mat = new MallTemplateMaterial();

            $mall_tem_mat->template_id = $template_id;
            $mall_tem_mat->material_id = $material_id;
            Util::initObjData($mall_tem_mat);

            Util::saveObjData($mall_tem_mat);

        }
        else
        {
            //恢复
            if($mall_tem_mat->is_delete == 1)
            {
                Util::recoverObjData($mall_tem_mat);
                Util::saveObjData($mall_tem_mat);
            }
        }



    }

    //取消选中
    public static function deleteRelation($material_id,$template_id)
    {
        $mall_tem_mat  = MallTemplateMaterial::model()->find("material_id=:material_id and  template_id=:template_id",
            array(":material_id" => $material_id,":template_id" => $template_id));

        if(empty($mall_tem_mat)==false)
        {
            //删除
            if($mall_tem_mat->is_delete == 0)
            {
                Util::deleteObjData($mall_tem_mat);
                Util::saveObjData($mall_tem_mat);
            }

        }
        else
        {

        }



    }



}
?>